<template>
  <div>
    <div>
      <el-form :inline="true" :model="user" class="demo-form-inline">

        <el-form-item label="培训计划">
          <el-select v-model="user.trainingPlanId" placeholder="请选择">
            <el-option
                v-for="item in trainingPlanList"
                :key="item.value"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="姓名">
          <el-input v-model="user.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="所属机构">
          <el-select v-model="user.agencyId" placeholder="请选择">
            <el-option
                v-for="item in agencyList"
                :key="item.value"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="show">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="clear">清空</el-button>
        </el-form-item>
        <el-form-item>
          <el-button  type="primary"  @click="exportData">导出</el-button>
        </el-form-item>

      </el-form>

      <div>
        <h1 v-show="tableData.length===0" style="margin-top: 200px">请先选择培训计划</h1>
        <div v-show="tableData.length!==0">
          <el-descriptions title="考试情况统计分析" direction="vertical" :column="4" border>
            <el-descriptions-item label="平均分/总分">{{ avgScore }}/{{ allScore}}</el-descriptions-item>
            <el-descriptions-item label="及格人数/总人数">{{ passNum }}/{{ unPassNum }}</el-descriptions-item>
            <el-descriptions-item label="及格率">{{ rateOfPass }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <el-table
            v-show="tableData.length!==0"
            id="tableId"
            v-loading="loading"
            max-height="500"
            highlight-current-row
            ref="multipleTable"
            tooltip-effect="dark"
            border
            :data="tableData"
            style="margin: 0 auto; width: 100%;"
        >
          <el-table-column prop="id" label="编号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" header-align="center" align="center"></el-table-column>
          <el-table-column prop="agencyId" label="归属机构" header-align="center" align="center">
            <template slot-scope="scope">
              {{ getAgencyName(scope.row.agencyId) }}
            </template>
          </el-table-column>
          <el-table-column prop="score" label="成绩" header-align="center" align="center"></el-table-column>
        </el-table>
      </div>

      <el-dialog :visible.sync="dialogVisible" :before-close="close">

        <el-table

            max-height="500"
            highlight-current-row
            ref="multipleTable"
            tooltip-effect="dark"
            border
            :data="userSituation"
            style="margin: 0 auto; width: 100%;"
        >
          <el-table-column prop="documentVideoId" label="视频文档编号" header-align="center"
                           align="center"></el-table-column>
          <el-table-column prop="type" label="文档视频名" header-align="center" align="center">
            <template slot-scope="scope">
              {{ getDocumentVideoName(scope.row.documentVideoId) }}
            </template>
          </el-table-column>
          <el-table-column prop="percentage" label="完成进度" header-align="center" align="center">
            <template slot-scope="scope">
              {{ scope.row.percentage }}%
            </template>
          </el-table-column>

        </el-table>
      </el-dialog>


    </div>

    <br>
    <!--分页工具条-->
    <footer>
      <el-pagination
          style="position:absolute;bottom: 20px;margin-left: 40vh"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :background="background"
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount">
      </el-pagination>
    </footer>
  </div>


</template>
<script>


import {addUser, changeUser, deleteUser, getAllUsers} from "@/api/user";
import {getAgencyList} from "@/api/agency";
import {getTrainingPlanList} from "@/api/trainingPlan";
import {getLearningSituationOfOnePlan} from "@/api/learningSituation";
import {getDocumentVideoList} from "@/api/documentVideo";
import {getExamSituationList, getExamSituationOfOnePlan} from "@/api/Score";
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      user: {},
      form: {},
      posts: [],
      multipleSelection: [],
      selectedIds: [],
      agencyList: [],
      formLabelWidth: "80px",
      theMajorOfMy: "",
      trainingPlanList: [],
      userSituation: [],
      documentVideoList: [],

      loading: false,
      //统计分析
      rateOfPass: 0,//及格率
      avgScore: 0,//均分
      allScore:0,//总分
      passNum: 0,//及格人数
      unPassNum: 0,//总人数


    }
  },
  methods: {

    show() {
      this.passNum=0;

      getExamSituationOfOnePlan(this.user, this.currentPage, this.pageSize).then((res) => {
        // console.log(res)
        if (res.data.code === 1) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
          if (this.tableData.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.show()
          }
          console.log(this.tableData)

          this.unPassNum = this.tableData.length; // 总人数
          let totalScore = 0; // 总分
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].score !== null) {
              let scores = parseInt(this.tableData[i].score.split('/')[0], '10');
              let allScore = parseInt(this.tableData[i].score.split('/')[1], '10');
              this.allScore=allScore;
              if(scores>=allScore*0.6){
                this.passNum+=1;
              }
              totalScore += scores;
            }
          }
          // 计算均分
          this.avgScore = totalScore / this.tableData.length;
          // 计算及格率
          this.rateOfPass = this.passNum / this.tableData.length;

        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {

      })
    },
    clear() {
      this.tableData = [];
      this.user = {}
    },
    add() {
      this.user = {};
      this.user.password = "1234567";
      this.addOrUpdate = true;
      this.dialogVisible = true;
    },
    addForm() {

      if (this.addOrUpdate) {
        addUser(this.user).then(res => {
          if (res.data.code === 1) {
            this.$message.success("保存成功")
            this.dialogVisible = false;
            this.show();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
        });
      } else {
        changeUser(this.user).then(res => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success("更新成功")
            this.dialogVisible = false;
            this.user.status = "正常";
            this.show();
          }
        }).catch(e => {
        });
      }

    },

    close() {
      this.dialogVisible = false;
      this.user = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.userSituation = this.tableData.filter(data => data.id == id)[0].learningSituation;
      this.dialogVisible = true;
    },

    getAllAgencyList() {
      getAgencyList().then((res) => {
        if (res.data.code === 1) {
          this.agencyList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getAgencyName(id) {
      let agency = this.agencyList.find(data => data.id === id);
      return agency ? agency.name : "";
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.show();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.show();
    },

    getTrainingsPlanList() {
      getTrainingPlanList().then((res) => {
        if (res.data.code === 1) {
          this.trainingPlanList = res.data.data;
        } else {
          console.log(res.data.msg);
        }
      }).catch((e) => {
      })
    },

    getDocumentVideoName(id) {
      const types = this.documentVideoList.find(t => t.id === id);
      return types ? types.name : '';
    },
    getDocumentVideoLists() {
      getDocumentVideoList().then((res) => {
        if (res.data.code === 1) {
          this.documentVideoList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getTrainingPlanName(id){
      const types = this.trainingPlanList.find(t => t.id === id);
      return types ? types.name : '';
    },


    //数据导出
    async exportData() {

      this.loading = true;
      this.currentPage = 1;
      this.pageSize = this.totalCount;


      try {
        await getExamSituationList(this.user).then((res) => {
          if(res.data.code===1){
            this.tableData=res.data.data;
            //将learningSituationList拆开放入属性中
            const data =this.tableData;

            // 创建工作簿对象
            const wb = XLSX.utils.book_new();

            // 将数据添加到工作簿中，假设 data 是一个二维数组或对象数组
            // 如果 data 是对象数组，使用 XLSX.utils.json_to_sheet(data)
            // 如果 data 是二维数组，使用 XLSX.utils.aoa_to_sheet(data)
            const ws = XLSX.utils.json_to_sheet(data);

            // 将工作表添加到工作簿中
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
            // 写入工作簿，生成 XLSX 文件
            const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
            // 使用 FileSaver 保存文件
            try {
              FileSaver.saveAs(
                  new Blob([wbout], {type: "application/octet-stream"}),
                  this.getTrainingPlanName(this.user.trainingPlanId)+"_考试成绩.xlsx"
              );
            } catch (e) {
              console.error(e);
            }

          }
        }).catch((e) => {})
      } finally {
        this.currentPage = 1;
        this.pageSize = 5;
        this.show();
        this.loading = false;
      }
    },


  },
  mounted() {
    this.getAllAgencyList();
    this.getTrainingsPlanList();
    this.getDocumentVideoLists();
  },
};
</script>


<style>
* {
  margin: 0;
  padding: 0;
}

.el-header {
  background-color: rgb(238, 241, 246);
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: white;
}

</style>
<script setup>
</script>
